package org.lhh.server.service.impl;

import org.lhh.server.common.api.JSONResult;
import org.lhh.server.config.web.exception.TestException;
import org.lhh.server.core.codec.slave.SlaveServerCodec;
import org.lhh.server.core.repository.EtlRepository;
import org.lhh.server.service.ISlaveService;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.www.SlaveServerStatus;
import org.springframework.stereotype.Service;

@Service
public class SlaveServerServiceImpl implements ISlaveService {


    @Override
    public void saveSlaveServer(SlaveServerCodec slaveServerCodec) {
        SlaveServer slaveServer = SlaveServerCodec.decodeSingle(slaveServerCodec);
        EtlRepository.saveSlaveServer(slaveServer);
    }

    @Override
    public void remove(Long id) {
        EtlRepository.deleteSlave(new LongObjectId(id));
    }

    @Override
    public JSONResult list() {
        return JSONResult.ok(SlaveServerCodec.encode(EtlRepository.getSlaveServers()));
    }

    @Override
    public JSONResult test(SlaveServerCodec slaveServerCodec) {
        SlaveServer slaveServer = SlaveServerCodec.decodeSingle(slaveServerCodec);
        try {
            SlaveServerStatus status = slaveServer.getStatus();
            String statusDescription = status.getStatusDescription();
            if ("Online".equals(statusDescription)) {
                return JSONResult.ok(status);
            } else {
                throw new TestException("子服务器连接失败，资源不可用");
            }
        } catch (Exception e) {
            throw new TestException(e.getMessage());
        }
    }
}
